<template>
  <Layout>
    <div class="coupon-container">
      <!-- 功能入口区域 -->
      <div class="function-area">
        <el-button type="primary" @click="handleCreateCoupon">新建优惠券</el-button>
        <div class="search-area">
          <el-form :inline="true" :model="searchForm" class="demo-form-inline">
            <el-form-item>
              <el-input
                v-model="searchForm.name"
                placeholder="请输入优惠券名称"
                clearable
                @keyup.enter="handleSearch"
              />
            </el-form-item>
            <el-form-item>
              <el-select v-model="searchForm.type" placeholder="优惠券类型" clearable>
                <el-option label="全部" value="" />
                <el-option label="满减券" :value="1" />
                <el-option label="折扣券" :value="2" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select v-model="searchForm.status" placeholder="状态" clearable>
                <el-option label="全部" value="" />
                <el-option label="上线中" :value="1" />
                <el-option label="已下线" :value="0" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <!-- 数据列表 -->
      <div class="data-table">
        <el-table
          :data="couponList"
          style="width: 100%"
          v-loading="loading"
          border
        >
          <el-table-column prop="name" label="优惠券名称" min-width="150" />
          <el-table-column label="优惠券类型" width="100">
            <template #default="scope">
              {{ getCouponTypeText(scope.row.type) }}
            </template>
          </el-table-column>
          <el-table-column label="优惠券内容" min-width="150">
            <template #default="scope">
              <div v-if="scope.row.type === 1">
                满{{ scope.row.threshold }}元减{{ scope.row.value }}元
              </div>
              <div v-else-if="scope.row.type === 2">
                满{{ scope.row.threshold }}元打{{ scope.row.value }}折
              </div>
            </template>
          </el-table-column>
          <el-table-column label="已领取/发行量" width="120">
            <template #default="scope">
              {{ scope.row.usedCount || 0 }}/{{ scope.row.quantity || 0 }}
            </template>
          </el-table-column>
          <el-table-column label="有效期" min-width="180">
            <template #default="scope">
              {{ formatTime(scope.row.startTime) }} 至 {{ formatTime(scope.row.endTime) }}
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                {{ scope.row.status === 1 ? '上线中' : '已下线' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="创建时间" min-width="180">
            <template #default="scope">
              {{ formatTime(scope.row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button
                link
                type="primary"
                size="small"
                @click="handleEdit(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                v-if="scope.row.status === 0"
                link
                type="success"
                size="small"
                @click="handleChangeStatus(scope.row, 1)"
              >
                上线
              </el-button>
              <el-button
                v-else
                link
                type="warning"
                size="small"
                @click="handleChangeStatus(scope.row, 0)"
              >
                下线
              </el-button>
              <el-button
                link
                type="danger"
                size="small"
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <!-- 空状态 -->
      <el-empty v-if="couponList.length === 0 && !loading" description="暂无数据" />
    </div>

    <!-- 优惠券详情弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑优惠券' : '新增优惠券'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="couponForm"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="优惠券名称" prop="name">
          <el-input v-model="couponForm.name" placeholder="请输入优惠券名称" maxlength="30" show-word-limit />
        </el-form-item>
        <el-form-item label="优惠券类型" prop="type">
          <el-radio-group v-model="couponForm.type">
            <el-radio :label="1">满减券</el-radio>
            <el-radio :label="2">折扣券</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item 
          :label="couponForm.type === 1 ? '满减金额' : '折扣比例'" 
          prop="value"
        >
          <el-input-number 
            v-model="couponForm.value" 
            :min="couponForm.type === 1 ? 0 : 0.1" 
            :max="couponForm.type === 1 ? 10000 : 9.9" 
            :precision="couponForm.type === 1 ? 0 : 1"
          />
          <span class="hint-text">{{ couponForm.type === 1 ? '元' : '折（如：7.5折）' }}</span>
        </el-form-item>
        <el-form-item label="使用门槛" prop="threshold">
          <el-input-number 
            v-model="couponForm.threshold" 
            :min="0" 
            :precision="0"
          />
          <span class="hint-text">元（0表示无门槛）</span>
        </el-form-item>
        <el-form-item label="发行数量" prop="quantity">
          <el-input-number v-model="couponForm.quantity" :min="1" :precision="0" />
          <span class="hint-text">张</span>
        </el-form-item>
        <el-form-item label="有效期" prop="validPeriod">
          <el-date-picker
            v-model="couponForm.validPeriod"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="couponForm.status">
            <el-radio :label="1">上线</el-radio>
            <el-radio :label="0">下线</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </Layout>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import Layout from '@/components/Layout.vue';
import { 
  getCouponList, 
  createCoupon, 
  updateCoupon, 
  deleteCoupon,
  updateCouponStatus
} from '@/api/coupon';

// 加载状态
const loading = ref(false);

// 优惠券列表数据
const couponList = ref<any[]>([]);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 搜索表单
const searchForm = reactive({
  name: '',
  type: '',
  status: ''
});

// 弹窗相关
const dialogVisible = ref(false);
const isEdit = ref(false);
const formRef = ref();

// 优惠券表单
const couponForm = reactive({
  objectId: '',
  name: '',
  type: 1,
  value: 0,
  threshold: 0,
  quantity: 100,
  validPeriod: [] as any[],
  usedCount: 0,
  status: 1
});

// 表单校验规则
const formRules = {
  name: [
    { required: true, message: '请输入优惠券名称', trigger: 'blur' },
    { max: 30, message: '优惠券名称不能超过30个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择优惠券类型', trigger: 'change' }
  ],
  value: [
    { required: true, message: '请输入优惠金额/折扣', trigger: 'blur' }
  ],
  quantity: [
    { required: true, message: '请输入发行数量', trigger: 'blur' }
  ],
  validPeriod: [
    { required: true, message: '请选择有效期', trigger: 'change' }
  ]
};

// 获取优惠券类型文本
const getCouponTypeText = (type: number) => {
  const typeMap: Record<number, string> = {
    1: '满减券',
    2: '折扣券'
  };
  return typeMap[type] || '未知';
};

// 格式化时间
const formatTime = (timeStr: string) => {
  if (!timeStr) return '';
  const date = new Date(timeStr);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    hour12: false
  }).replace(/\//g, '-');
};

// 加载优惠券列表
const loadCouponList = async () => {
  loading.value = true;
  try {
    const params: any = {
      limit: pageSize.value,
      skip: (currentPage.value - 1) * pageSize.value
    };
    
    // 添加搜索条件
    const whereConditions: any = {};
    
    if (searchForm.name) {
      whereConditions.name = { $regex: `.*${searchForm.name}.*` };
    }
    
    if (searchForm.type !== '') {
      whereConditions.type = Number(searchForm.type);
    }
    
    if (searchForm.status !== '') {
      whereConditions.status = Number(searchForm.status);
    }
    
    if (Object.keys(whereConditions).length > 0) {
      params.where = JSON.stringify(whereConditions);
    }
    
    const response: any = await getCouponList(params);
    couponList.value = response.results || [];
    total.value = response.count || 0;
  } catch (error) {
    console.error('获取优惠券列表失败:', error);
    ElMessage.error('获取优惠券列表失败');
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  loadCouponList();
};

// 处理重置
const handleReset = () => {
  searchForm.name = '';
  searchForm.type = '';
  searchForm.status = '';
  currentPage.value = 1;
  loadCouponList();
};

// 处理页码变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  loadCouponList();
};

// 处理每页条数变化
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
  loadCouponList();
};

// 处理新建优惠券
const handleCreateCoupon = () => {
  isEdit.value = false;
  resetForm();
  dialogVisible.value = true;
};

// 处理编辑
const handleEdit = (row: any) => {
  isEdit.value = true;
  resetForm();
  
  // 填充表单数据
  couponForm.objectId = row.objectId;
  couponForm.name = row.name;
  couponForm.type = row.type;
  couponForm.value = row.value;
  couponForm.threshold = row.threshold;
  couponForm.quantity = row.quantity;
  couponForm.usedCount = row.usedCount || 0;
  couponForm.status = row.status;
  
  // 设置有效期
  if (row.startTime && row.endTime) {
    couponForm.validPeriod = [row.startTime, row.endTime];
  }
  
  dialogVisible.value = true;
};

// 处理状态变更
const handleChangeStatus = (row: any, status: number) => {
  const statusText = status === 1 ? '上线' : '下线';
  ElMessageBox.confirm(`是否确认${statusText}该优惠券？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await updateCouponStatus(row.objectId, status);
      ElMessage.success(`优惠券已${statusText}`);
      loadCouponList();
    } catch (error) {
      console.error(`优惠券${statusText}失败:`, error);
      ElMessage.error(`优惠券${statusText}失败`);
    }
  }).catch(() => {});
};

// 处理删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm('是否确认删除该优惠券？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteCoupon(row.objectId);
      ElMessage.success('优惠券已删除');
      loadCouponList();
    } catch (error) {
      console.error('删除优惠券失败:', error);
      ElMessage.error('删除优惠券失败');
    }
  }).catch(() => {});
};

// 重置表单
const resetForm = () => {
  couponForm.objectId = '';
  couponForm.name = '';
  couponForm.type = 1;
  couponForm.value = 0;
  couponForm.threshold = 0;
  couponForm.quantity = 100;
  couponForm.validPeriod = [];
  couponForm.usedCount = 0;
  couponForm.status = 1;
  
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 处理提交
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        if (!couponForm.validPeriod || couponForm.validPeriod.length !== 2) {
          ElMessage.error('请选择有效的时间范围');
          return;
        }

        const data = {
          name: couponForm.name,
          type: couponForm.type,
          value: couponForm.value,
          threshold: couponForm.threshold,
          quantity: couponForm.quantity,
          startTime: { __type: 'Date', iso: new Date(couponForm.validPeriod[0]).toISOString() },
          endTime: { __type: 'Date', iso: new Date(couponForm.validPeriod[1]).toISOString() },
          status: couponForm.status
        };
        
        if (isEdit.value) {
          // 编辑时保留已使用数量
          Object.assign(data, { usedCount: couponForm.usedCount });
          await updateCoupon(couponForm.objectId, data);
          ElMessage.success('编辑成功');
        } else {
          // 新建时设置已使用数量为0
          Object.assign(data, { usedCount: 0 });
          await createCoupon(data);
          ElMessage.success('新增成功');
        }
        
        dialogVisible.value = false;
        loadCouponList();
      } catch (error) {
        console.error('保存优惠券失败:', error);
        ElMessage.error('保存优惠券失败');
      }
    }
  });
};

// 页面加载时获取数据
onMounted(() => {
  loadCouponList();
});
</script>

<style scoped>
.coupon-container {
  padding: 0;
}

.function-area {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  align-items: center;
  flex-wrap: wrap;
}

.search-area {
  flex-grow: 1;
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.data-table {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.hint-text {
  margin-left: 8px;
  color: #909399;
  font-size: 14px;
}
</style> 